<template>
  <a-card style="width: 100%">
    <div ref="chartsRef" id="main" style="width: 100%; height: 240px"></div>
  </a-card>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

const chartsRef = ref("");

const generateRandomData = () => {
  return Array.from({ length: 7 }, () => Math.floor(Math.random() * 300));
};

let myChart = null;

onMounted(() => {
  const chartDom = document.getElementById("main");
  myChart = echarts.init(chartDom);

  // 生成随机数据
  const randomData = generateRandomData();

  const option = {
    title: {
      text: "每日活跃用户",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: randomData, // 使用随机数据
        type: "line",
      },
    ],
  };

  myChart.setOption(option);

  // 监听窗口尺寸变化，调整图表大小
  window.addEventListener("resize", handleResize);
});

// 处理窗口尺寸变化的回调
const handleResize = () => {
  if (myChart) {
    myChart.resize(); // 调整图表尺寸
  }
};

// 清理事件监听器
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose(); // 销毁图表实例
  }
  window.removeEventListener("resize", handleResize); // 移除 resize 事件监听器
});
</script>

<style lang="scss" scoped>
</style>
